<?php
/**
 * 菜单及权限
 * Created by PhpStorm.
 * User: LRChang
 * Date: 2018/6/5
 * Time: 16:24
 * Mail: hjklrchang@qq.com
 */

namespace app\open\model;

use traits\model\SoftDelete;
use app\open\model\User;
use app\open\model\Role;
class Menu extends Common
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';


    public function getSort() {
        return $this->order('sort')->select();
    }

    /**
     * @param int $role_id
     * @return Menu[]|false
     * @throws \think\exception\DbException
     */
    public function role($role_id) {

        $role = Role::get($role_id);
        $menus = explode(',',$role->menus);

        $list = $this->getSort();
        //选中
        foreach ($list AS $key=>$value) {
            if(in_array($value->id,$menus)) {
                $list[$key]['checked'] = true;
            }
        }

        return $list;
    }
    /**
     * @param int $user_id
     * @return Menu[]|false
     * @throws \think\exception\DbException
     */
    public function user($user_id) {

        $user = User::get($user_id);
        $menus = $user->getMenus();
        $list = $this->whereIn('id',$menus)->order('sort')->select();

        return Arr2Tree($list);
    }
}